package com.leyou.common.utils;

import com.aliyun.oss.OSS;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;


/**
 * @author xhh
 * @date 2022/3/22
 */
@Component
public class AliOss{
    private static final String[] IMAGE_TYPE=new String[]{
            ".bmp",".jpg",".jpeg",".gif",".png"
    };
    @Autowired
    private OSS ossClient;
    @Value("${aliyun.bucketName}")
    private String bucketName;
    @Value("${aliyun.urlPrefix}/")
    private String urlPrefix;

    public String upload(MultipartFile uploadFile){
        boolean isLegal=false;
        if(uploadFile==null){
            return "";
        }
        for(String type: IMAGE_TYPE){
            if(StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),type)){
                isLegal=true;
                break;
            }
        }
        if(!isLegal){
            return "";
        }
        String fileName=uploadFile.getOriginalFilename();
        String filePath=getFilePath(fileName);
        //上传阿里云
        try {
            System.out.println(bucketName);
            System.out.println(filePath);
            ossClient.putObject(bucketName,filePath,new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        System.err.println(filePath);
        return urlPrefix+filePath;
    }

    private String getFilePath(String sourceFileName){
        DateTime dateTime=new DateTime();
        String s="images/"+dateTime.toString("yyyy")+"/"+dateTime.toString("MM")+"/"
                +dateTime.toString("dd")+"/"+System.currentTimeMillis()+ RandomUtils.nextInt(100,9999)+"."+
                StringUtils.substringAfterLast(sourceFileName,".");
        return s;
    }
}
